<template>
  <div class="good">
    <div class="mybody">
      <!-- 标题和搜索区域 -->
      <div class="header">
        <div class="search-area">
          <el-input
            v-model="searchOrderNo"
            placeholder="请输入订单号"
            style="width: 200px; margin-right: 10px"
            clearable
          />
          <!-- <el-select v-model="searchState" placeholder="订单状态" style="width: 150px; margin-right: 10px" clearable>
            <el-option label="待发货" value="待发货" />
            <el-option label="待收货" value="待收货" />
            <el-option label="已完成" value="已完成" />
          </el-select> -->
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </div>
      </div>

      <!-- 表单 -->
      <el-form class="mytable">
        <el-table :data="orderList" border stripe style="width: 100%" ref="tableRef" align="center" v-loading="loading">
          <el-table-column label="ID" width="60" prop="id" align="center" />
          <el-table-column label="订单编号" width="180" prop="orderNo" align="center" />
          <el-table-column label="总价" width="100" prop="totalPrice" align="center">
            <template #default="scope">
              ¥{{ scope.row.totalPrice }}
            </template>
          </el-table-column>
          <el-table-column label="收货人" width="100" prop="linkUser" align="center" />
          <el-table-column label="联系电话" width="120" prop="linkPhone" align="center" />
          <el-table-column label="收货地址" prop="linkAddress" align="center" show-overflow-tooltip />
          <el-table-column label="订单状态" width="100" prop="state" align="center">
            <template #default="scope">
              <el-tag :type="getOrderStateType(scope.row.state)">{{ scope.row.state }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="下单时间" width="180" prop="createTime" align="center" />
          <el-table-column label="操作" width="150" align="center">
            <template #default="scope">
              <el-button 
                v-if="scope.row.state === '待发货'" 
                type="success" 
                size="small" 
                @click="handleDelivery(scope.row)"
              >
                发货
              </el-button>
              <el-button 
                type="primary" 
                size="small" 
                @click="handleViewOrder(scope.row)"
              >
                查看
              </el-button>
              <el-button 
                type="danger" 
                size="small" 
                @click="handleDelete(scope.row)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
    </div>

    <!-- 分页器 -->
    <div class="demo-pagination-block">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[5, 10, 20, 50]"
        :total="total"
        layout="total, sizes, prev, pager, next"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 订单详情对话框 -->
    <el-dialog 
      v-model="dialogVisible" 
      title="订单详情" 
      width="60%"
      destroy-on-close
    >
      <div v-if="currentOrder">
        <div class="order-info">
          <h3>基本信息</h3>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="订单编号">{{ currentOrder.orderNo }}</el-descriptions-item>
            <el-descriptions-item label="下单时间">{{ currentOrder.createTime }}</el-descriptions-item>
            <el-descriptions-item label="订单状态">
              <el-tag :type="getOrderStateType(currentOrder.state)">{{ currentOrder.state }}</el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="订单总价">¥{{ currentOrder.totalPrice }}</el-descriptions-item>
            <el-descriptions-item label="收货人">{{ currentOrder.linkUser }}</el-descriptions-item>
            <el-descriptions-item label="联系电话">{{ currentOrder.linkPhone }}</el-descriptions-item>
            <el-descriptions-item label="收货地址" :span="2">{{ currentOrder.linkAddress }}</el-descriptions-item>
          </el-descriptions>
        </div>
        
        <div class="order-goods" v-if="currentOrder.goods">
          <h3>商品信息</h3>
          <div class="goods-list">
            <div v-for="(item, index) in parseGoods(currentOrder.goods)" :key="index" class="goods-item">
              <div class="goods-info">
                <div>商品名称：{{ item.name }}</div>
                <div>单价：¥{{ item.price }}</div>
                <div>数量：{{ item.num }}</div>
                <div>小计：¥{{ (item.price * item.num).toFixed(2) }}</div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, inject } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';

// 注入axios
const $axios = inject('$axios');

// 数据定义
const orderList = ref([]);
const loading = ref(false);
const dialogVisible = ref(false);
const currentOrder = ref(null);
const total = ref(0);

// 分页相关
const currentPage = ref(1);
const pageSize = ref(10);

// 搜索条件
const searchOrderNo = ref('');
const searchState = ref('');

// 获取订单列表
const fetchOrders = async () => {
  loading.value = true;
  try {
    const response = await $axios.get('/api/order/page', {
      params: {
        pageNum: currentPage.value,
        pageSize: pageSize.value,
        orderNo: searchOrderNo.value,
        state: searchState.value
      }
    });
    if (response.code === '200') {
      orderList.value = response.data.records;
      total.value = response.data.total;
    } else {
      ElMessage.error('获取订单列表失败');
    }
  } catch (error) {
    console.error('获取订单列表出错:', error);
    ElMessage.error('获取订单列表出错');
  } finally {
    loading.value = false;
  }
};

// 处理页码变化
const handleCurrentChange = (newPage) => {
  currentPage.value = newPage;
  fetchOrders();
};

// 处理每页条数变化
const handleSizeChange = (newSize) => {
  pageSize.value = newSize;
  currentPage.value = 1;
  fetchOrders();
};

// 搜索订单
const handleSearch = () => {
  currentPage.value = 1;
  fetchOrders();
};

// 重置搜索条件
const resetSearch = () => {
  searchOrderNo.value = '';
  searchState.value = '';
  currentPage.value = 1;
  fetchOrders();
};

// 查看订单详情
const handleViewOrder = (order) => {
  currentOrder.value = order;
  dialogVisible.value = true;
};

// 发货操作
const handleDelivery = (order) => {
  ElMessageBox.confirm('确定要为该订单发货吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const response = await $axios.get(`/api/order/delivery/${order.orderNo}`);
      if (response.code === '200') {
        ElMessage.success('发货成功');
        fetchOrders();
      } else {
        ElMessage.error(response.message || '发货失败');
      }
    } catch (error) {
      console.error('发货操作出错:', error);
      ElMessage.error('发货操作出错');
    }
  }).catch(() => {
    // 取消发货
    ElMessage.info('已取消发货操作');
  });
};

// 删除订单操作
const handleDelete = (order) => {
  ElMessageBox.confirm('确定要删除该订单吗？此操作不可恢复', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const response = await $axios.delete(`/api/order/${order.id}`);
      if (response.code === '200') {
        ElMessage.success('删除成功');
        fetchOrders();
      } else {
        ElMessage.error(response.message || '删除失败');
      }
    } catch (error) {
      console.error('删除订单出错:', error);
      ElMessage.error('删除订单出错');
    }
  }).catch(() => {
    // 取消删除
    ElMessage.info('已取消删除操作');
  });
};

// 根据订单状态获取标签类型
const getOrderStateType = (state) => {
  switch (state) {
    case '待付款':
      return 'info';
    case '待发货':
      return 'warning';
    case '待收货':
      return 'primary';
    case '已完成':
      return 'success';
    default:
      return '';
  }
};

// 解析商品信息
const parseGoods = (goodsStr) => {
  try {
    return JSON.parse(goodsStr);
  } catch (e) {
    console.error('解析商品信息出错:', e);
    return [];
  }
};

// 页面加载时获取数据
onMounted(() => {
  fetchOrders();
});
</script>

<style scoped>
.good {
  padding: 30px;
  width: 100%;
  height: 100%;
  box-sizing: border-box;
}

.mybody {

  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
  padding: 0 10px;
}

.search-area {
  display: flex;
  align-items: center;
}

.mytable {
  text-align: center;
  width: 100%;
}

.demo-pagination-block {
  margin-top: 20px;
  text-align: center;
}

/* 订单详情样式 */
.order-info,
.order-goods {
  margin-bottom: 20px;
}

.order-info h3,
.order-goods h3 {
  margin-bottom: 10px;
  font-size: 16px;
  font-weight: bold;
}

.goods-list {
  border: 1px solid #ebeef5;
  border-radius: 4px;
}

.goods-item {
  display: flex;
  padding: 12px;
  border-bottom: 1px solid #ebeef5;
}

.goods-item:last-child {
  border-bottom: none;
}

.goods-info {
  flex: 1;
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 10px;
  align-items: center;
}

/* 表格样式优化 */
:deep(.el-table) {
  width: 100%;
}

:deep(.el-form) {
  width: 100%;
  margin: 0;
  padding: 0;
}

:deep(.el-table__header) {
  width: 100% !important;
}

:deep(.el-table__body) {
  width: 100% !important;
}
</style>